/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.atnoce.onepass.view;

import com.atnoce.onepass.Start;
import com.atnoce.onepass.core.BackService;
import com.atnoce.onepass.core.SecurityController;
import com.atnoce.onepass.dao.CommonDao;
import com.atnoce.onepass.dao.DirTypeDao;
import com.atnoce.onepass.dao.PasswordItemDao;
import com.atnoce.onepass.pojo.DirType;
import com.atnoce.onepass.pojo.PasswordItem;
import com.atnoce.onepass.utils.*;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import org.apache.commons.lang.StringUtils;

import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author atnoce.com
 * @date 2016/11/4 1:32
 * @since 1.0.0
 */
public class IndexLayoutController {
    @FXML
    private ListView<String> classType;
    @FXML
    private TableView<PasswordItem> tableView;
    @FXML
    private TableColumn<PasswordItem, String> accountColumn;
    @FXML
    private TableColumn<PasswordItem,String> remarkStrColumn;
    @FXML
    private Button addDirTypeBtn;
    @FXML
    private Button addPassItemBtn;
    @FXML
    private Button optionsBtn;
    @FXML
    private Button helpBtn;
    @FXML
    private TextField showUsername;
    @FXML
    private TextField showPass;
    @FXML
    private TextArea showBeizhu;
    @FXML
    private Button copyUsernameBtn;
    @FXML
    private Button copyPassBtn;
    @FXML
    private Button showPassBtn;
    @FXML
    private TextField searchInput;
    @FXML
    private Button searchBtn;
    @FXML
    private Button lockBtn;
    @FXML
    private ImageView coludImg;
    @FXML
    private Button coludBtn;

    private Start start;


    public void setStart(Start start){
        this.start=start;
    }
    private final PasswordItemDao pd=new PasswordItemDao();
    private final DirTypeDao ctd=new DirTypeDao();
    private final CommonDao cd=new CommonDao();
    private ObservableList<DirType> dirTypes=null;
    private final ObservableList<String> ol= FXCollections.observableArrayList();
    private ObservableList<PasswordItem> pitems=null;
    @FXML
    private void initialize(){
        initTable();
        initLeftList();
        initBtnEventHandle();
        initShowPanel();
        classType.getSelectionModel().select(0);
        showBeizhu.setWrapText(true);
        searchInput.setOnKeyReleased(e->search());
        initTip();

        if (StringUtils.equals("false",Cache.getProConfig(Const.ACTIONCLOUD))){
            coludBtn.setVisible(false);
            System.out.println("colud btn show false");
        }
    }

    private void initTip() {
        addDirTypeBtn.setTooltip(CommonUtil.getTooltip("添加分类", 14));
        addPassItemBtn.setTooltip(CommonUtil.getTooltip("添加密码项", 14));
        optionsBtn.setTooltip(CommonUtil.getTooltip("系统全局配置", 14));
        helpBtn.setTooltip(CommonUtil.getTooltip("获取帮助信息", 14));
        lockBtn.setTooltip(CommonUtil.getTooltip("锁定主界面", 14));
        coludBtn.setTooltip(CommonUtil.getTooltip("立即进行同步", 14));
        searchInput.setTooltip(CommonUtil.getTooltip("输入任意字符全局搜索结果", 14));
        classType.setTooltip(CommonUtil.getTooltip("右键可显示更多菜单",14));
        tableView.setTooltip(CommonUtil.getTooltip("双击在下方显示密码信息，鼠标右键点击显示更多菜单", 14));
        showUsername.setTooltip(CommonUtil.getTooltip("双击复制账号", 14));
        showPass.setTooltip(CommonUtil.getTooltip("双击复制密码", 14));
    }

    private void search() {
        String str=searchInput.getText().trim();

        try {
            ObservableList<PasswordItem> search = cd.search(str);
            for(PasswordItem pi:search){
                pi.setAccount(SecurityController.getSecurityInstence().AESdecrypt(pi.getAccount(), Cache.getKey()));
            }
            tableView.setItems(search);
        } catch (SQLException ex) {
            CommonUtil.alert(Alert.AlertType.ERROR,"查询失败","全文检索发生错误！错误信息:"+ex.getMessage(),"错误").showAndWait();
        }catch(ClassNotFoundException e){
            CommonUtil.alert(Alert.AlertType.ERROR,"查询失败","找不到数据库驱动！错误信息:"+e.getMessage(),"错误").showAndWait();
        } catch (Exception ex) {
            CommonUtil.alert(Alert.AlertType.ERROR,"查询失败","解密时发生错误::"+ex.getMessage(),"错误").showAndWait();
        }
    }

    private void initShowPanel() {
        showUsername.textProperty().addListener((observable,oldValue,newValue)->{
            copyUsernameBtn.setDisable(StringUtils.isBlank(newValue));
        });
        showPass.textProperty().addListener((observable,oldValue,newValue)->{
            copyPassBtn.setDisable(StringUtils.isBlank(newValue));
            showPassBtn.setDisable(StringUtils.isBlank(newValue));

        });
    }

    private void initBtnEventHandle() {
        addDirTypeBtn.setOnAction(e->addDirTypeBtnHandler());
        addPassItemBtn.setOnAction(e->addPassItemBtnHandler(null));
        optionsBtn.setOnAction(e->optionsBtnHandler());
        helpBtn.setOnAction(e->helpBtnHandler());
        lockBtn.setOnAction(e->lockBtnHandler());
        coludBtn.setOnAction(e->execColudSynce());
        copyUsernameBtn.setOnAction(e->copyUsername());
        copyPassBtn.setOnAction(e->copyPassword());
        showPassBtn.setOnAction(e->showPassword());
        showUsername.setOnMouseClicked((MouseEvent event)->{
            if(event.getButton().equals(MouseButton.PRIMARY)&&event.getClickCount()==2){
                copyUsername();
            }
        });
        showPass.setOnMouseClicked((MouseEvent event)->{
            if(event.getButton().equals(MouseButton.PRIMARY)&&event.getClickCount()==2){
                copyPassword();
            }
        });
    }

    private void showPassword() {
        String text = showPassBtn.getText();
        if (StringUtils.equals("显示",text)){
            PasswordItem selectedItem = tableView.getSelectionModel().getSelectedItem();
            if (selectedItem!=null){
                try {
                    showPass.setText(SecurityController.getSecurityInstence().AESdecrypt(selectedItem.getPasswordStr(), Cache.getKey()));
                    showPassBtn.setText("隐藏");
                } catch (Exception ex) {
                    CommonUtil.alert(Alert.AlertType.ERROR,"解密失败",ex.getMessage(),"错误").showAndWait();
                    return;
                }
            }
        }else{
            showPass.setText("*********");
            showPassBtn.setText("显示");
        }

    }

    private void copyPassword() {
        TextField _tmpPassField=new TextField();
        if(StringUtils.isNotBlank(showPass.getText())){
            PasswordItem selectedItem = tableView.getSelectionModel().getSelectedItem();
            try {
                _tmpPassField.setText(SecurityController.getSecurityInstence().AESdecrypt(selectedItem.getPasswordStr(), Cache.getKey()));
                _tmpPassField.selectAll();
                _tmpPassField.copy();
            } catch (Exception ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,"解密失败",ex.getMessage(),"错误").showAndWait();
                return;
            }
        }
    }

    private void copyUsername() {
        if(StringUtils.isNotBlank(showUsername.getText())){
            showUsername.selectAll();
            showUsername.copy();
        }
    }

    private void execColudSynce() {
        if(Boolean.valueOf(Cache.getProConfig(Const.ACTIONCLOUD))){
            try {
                BackService.startSyncService(this,coludImg,SecurityController.getSecurityInstence().decryptColudAccount(Cache.getProConfig(Const.COLUDACCOUNT),Cache.getKey()));
            } catch (Exception e) {
                CommonUtil.alert(Alert.AlertType.ERROR,"同步出现问题！","错误详情："+e.getMessage(),"错误").showAndWait();
                e.printStackTrace();
            }
        }
    }

    private void lockBtnHandler() {
        start.initLoginLayout(false);
    }

    private void helpBtnHandler() {
        /*DirectoryChooser chooser=new DirectoryChooser();
        chooser.setTitle("选择数据文件存放路径");
        File showDialog = chooser.showDialog(onepass.getPrimaryStage());
        System.out.println(toJavaFilePath(showDialog.getAbsolutePath()));
        System.out.println(showDialog.getAbsolutePath());*/
        // new ColudController().sync();
        //onepass.showAbout();
        try{
            FXMLLoader loader=new FXMLLoader();
            loader.setLocation(IndexLayoutController.class.getResource("ShowAbout.fxml"));
            BorderPane bp=loader.load();

            Stage aboutStage=new Stage();
            aboutStage.setTitle("关于onepass");
            aboutStage.initModality(Modality.WINDOW_MODAL);
            //aboutStage.initStyle(StageStyle.UNDECORATED);
            aboutStage.initOwner(start.getStage());
            Scene scene=new Scene(bp);
            aboutStage.setScene(scene);
            aboutStage.showAndWait();

        }catch(IOException e){
        }
    }

    private void optionsBtnHandler() {
        start.showPreferencesDialog();
    }

    private void addPassItemBtnHandler(PasswordItem passwordItem) {
        PasswordItem pi=passwordItem==null?new PasswordItem():passwordItem;
        Cache.setIndexLeftSelectedDirtype(classType.getSelectionModel().getSelectedItem());
        boolean okClicked = start.showPassEditDialog(pi);
        if(okClicked){
            String um = null;
            try {
                um = SecurityController.getSecurityInstence().AESdecrypt(pi.getAccount(), Cache.getKey());
            } catch (Exception ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,"添加失败","添加密码项目时发生错误："+ex.getMessage(),"错误").showAndWait();
                return;
            }
            coludImg.setImage(new Image(IndexLayoutController.class.getResourceAsStream("image/colud_change.png")));
            pi.setAccount(um);
            tableView.getItems().add(pi);
            ObservableList<String> items = classType.getItems();

            for(int a=0;a<items.size();a++){
                if(StringUtils.equals(items.get(a), Cache.getAddPassItemSelectDirtype())){
                    classType.getSelectionModel().select(a);
                    break;
                }
            }
        }
        Cache.setAddPassItemSelectDirtype(null);
        Cache.setIndexLeftSelectedDirtype(null);
    }

    private void addDirTypeBtnHandler() {
        TextInputDialog dialog = new TextInputDialog("");
        dialog.setTitle("添加分类");
        dialog.setHeaderText(null);
        dialog.setContentText("请输入分类名称:");

        Optional<String> result = dialog.showAndWait();

        result.ifPresent(name -> {
            if(StringUtils.isNotBlank(name.trim())){
                if(name.trim().length()>20){
                    CommonUtil.alert(Alert.AlertType.ERROR,"添加失败","分类名称不能超过20个字符！","添加失败").showAndWait();
                }else{
                    try {
                        DirType dirType = new DirType(name.trim());
                        Map<String, Object> addres = ctd.addDirType(dirType);
                        if((boolean)addres.get("flag")){
                            Map<QueueType,String> queue=new HashMap<>();
                            queue.put(QueueType.DIRCLASS,dirType.getDirId());
                            Cache.addUpdateModifyTimeQueue(queue);
                            BackService.startUpdateModifyTimeService();

                            ol.add(dirType.getDirName());
                            dirTypes.add(dirType);
                            coludImg.setImage(new Image(IndexLayoutController.class.getResourceAsStream("image/colud_change.png")));
                        }else{
                            CommonUtil.alert(Alert.AlertType.ERROR,"添加失败","分类添加失败!错误信息："+addres.get("msg"),"添加失败").showAndWait();
                        }
                    } catch (Exception e) {
                        CommonUtil.alert(Alert.AlertType.ERROR,"添加失败","添加分类发生系统错误！"+e.getMessage(),"添加失败").showAndWait();
                    }
                }
            }else{
                CommonUtil.alert(Alert.AlertType.ERROR,"添加失败","分类名称不能为空！","添加失败").showAndWait();
            }
        });
    }

    public void initLeftList() {
        try {
            ol.clear();
            dirTypes = ctd.getDirTypes();
            for (DirType dirType : dirTypes) {

                ol.add(dirType.getDirName());
            }
            //classType.refresh();
            classType.setItems(ol);
        } catch (SQLException e) {
            CommonUtil.alert(Alert.AlertType.ERROR,"初始化分类列表错误!","读取分类列表发生异常！"+e.getMessage(),"错误").showAndWait();
        }catch(ClassNotFoundException e){
            CommonUtil.alert(Alert.AlertType.ERROR,"初始化分类列表错误!","找不到数据库驱动！"+e.getMessage(),"错误").showAndWait();
        }
        //	classType.setCellFactory((ListView<DirType> arg0) -> new ListCell<DirType>(){
//            public void updateItem(DirType item,boolean empty){
//                super.updateItem(item, empty);
//                if(item!=null&&!empty){
//                    this.setText(item.getDirName());
//                }
//            }
//        });
        classType.getSelectionModel().selectedItemProperty().addListener((ObservableValue<? extends String> ov,
                                                                          String old_val,String new_val)->{
            updateTable(new_val);
        });
        initLiftRightContextMenu();
    }

    private void initLiftRightContextMenu() {
        //为分类初始化右键菜单
        final ContextMenu contextMenu = new ContextMenu();
        contextMenu.setOnShowing((WindowEvent e) -> {
            //System.out.println("showing");
        });
        contextMenu.setOnShown((WindowEvent e) -> {
            //System.out.println("shown");
        });

        MenuItem item1 = new MenuItem("删除分类");
        item1.setOnAction((ActionEvent e) -> {
            if(classType.getItems().size()==1){
                CommonUtil.alert(Alert.AlertType.ERROR,"不能删除该分类","至少要保留一个分类！","错误").showAndWait();
                return;
            }
            String selectedItem = classType.getSelectionModel().getSelectedItem();
            Alert alert=new Alert(Alert.AlertType.CONFIRMATION);
            alert.setHeaderText("确定要删除该分类吗？");
            alert.setContentText("删除分类会将该分类下的所有密码项删除!");
            Optional<ButtonType> showAndWait = alert.showAndWait();
            if(showAndWait.get().getButtonData()== ButtonBar.ButtonData.OK_DONE){
                try {
                    //执行删除分类逻辑
                    //删除子项
                    pd.deletePasswordItemFromDirType(selectedItem);
                    //删除分类
                    if(ctd.deleteDirType(selectedItem)){
                        ol.remove(selectedItem);
                        DirType dt=null;
                        for(DirType dirType:dirTypes){
                            if(StringUtils.equals(dirType.getDirName(), selectedItem)){
                                dt=dirType;
                                break;
                            }
                        }
                        if(dt!=null)
                            dirTypes.remove(dt);
                    }
                    //使用后服务为记录添加modifyTime
                    BackService.startUpdateModifyTimeService();
                } catch (SQLException ex) {
                    CommonUtil.alert(Alert.AlertType.ERROR,"删除分类失败","系统删除分类时发生错误！错误信息："+
                            ex.getMessage(),"错误").showAndWait();
                }catch(ClassNotFoundException ex){
                    CommonUtil.alert(Alert.AlertType.ERROR,"删除分类失败","找不到数据库驱动！错误信息："+
                            ex.getMessage(),"错误").showAndWait();
                }
            }
        });
        MenuItem item2 = new MenuItem("添加记录");
        item2.setOnAction((ActionEvent e) -> {
            addPassItemBtnHandler(null);
        });
        MenuItem item3 = new MenuItem("重命名");
        item3.setOnAction((ActionEvent e) -> {
            String selectedItem = classType.getSelectionModel().getSelectedItem();
            if(selectedItem==null){
                CommonUtil.alert(Alert.AlertType.WARNING,"操作无效","请将鼠标放在要修改的密码项上再点击鼠标右键！","错误").show();
                return;
            }
            TextInputDialog dialog = new TextInputDialog(selectedItem);
            dialog.setTitle("重命名");
            dialog.setHeaderText("分类名称不能超过20个字符");
            dialog.setContentText("请输入新的分类名称:");

            Optional<String> result = dialog.showAndWait();

            result.ifPresent(name -> {
                if(StringUtils.isNotBlank(name.trim())&&!StringUtils.equals(selectedItem, name)){
                    if(name.trim().length()>20){
                        CommonUtil.alert(Alert.AlertType.ERROR,"重命名失败","分类名称不能大于20个字符！","错误").showAndWait();
                        return;
                    }
                    try {
                        if(ctd.renameDirType(selectedItem, name.trim())){
                            Map<QueueType,String> queue=new HashMap<>();
                            queue.put(QueueType.DIRCLASS,ctd.getDirTypeByName(name.trim()).getDirId());
                            Cache.addUpdateModifyTimeQueue(queue);
                            BackService.startUpdateModifyTimeService();

                            classType.getItems().remove(classType.getSelectionModel().getSelectedIndex());
                            classType.getItems().add(classType.getSelectionModel().getSelectedIndex()+1, name.trim());
                        }
                    } catch (SQLException ex) {
                        CommonUtil.alert(Alert.AlertType.ERROR,"重命名失败","重命名分类名称时发生系统错误！错误信息："+
                                ex.getMessage(),"错误").showAndWait();
                    }catch(ClassNotFoundException ex){
                        CommonUtil.alert(Alert.AlertType.ERROR,"重命名失败","找不到数据库驱动！错误信息："+ex.getMessage(),"错误").showAndWait();
                    }
                }
            });

        });
        contextMenu.getItems().addAll(item2,item3, item1);
        classType.setContextMenu(contextMenu);
        //给tableView添加右键菜单
        //tableView.setContextMenu(contextMenu);
    }

    /**
     * 更新密码项目列表
     * @param new_val 分类ID
     */
    private void updateTable(String new_val) {
        if(StringUtils.isNotBlank(new_val))
            try {
                pitems = pd.getPasswordsFormDirName(new_val);
                if(pitems!=null){
                    pitems.stream().forEach((p) -> {
                        try {
                            p.setAccount(SecurityController.getSecurityInstence().AESdecrypt(p.getAccount(), Cache.getKey()));
                        } catch (Exception ex) {
                            CommonUtil.alert(Alert.AlertType.ERROR,"更新密码列表失败","解密失败！错误信息："+
                                    ex.getMessage(),"错误").showAndWait();
                            return;
                        }
                    });
                    tableView.setItems(pitems);
                }

            } catch (SQLException e) {
                CommonUtil.alert(Alert.AlertType.ERROR,"更新密码列表失败","获取密码列表时发生系统错误！错误信息："+
                        e.getMessage(),"错误").showAndWait();
            }catch(ClassNotFoundException e){
                CommonUtil.alert(Alert.AlertType.ERROR,"更新密码列表失败","找不到数据库驱动！错误信息："+
                        e.getMessage(),"错误").showAndWait();
            }
    }

    private void initTable() {
        accountColumn.setCellValueFactory(cellData->cellData.getValue().accountProperty());
        remarkStrColumn.setCellValueFactory(cellData->cellData.getValue().remarkStrProperty());

        tableView.setOnMouseClicked((MouseEvent event) -> {
            if(tableView.getSelectionModel().getSelectedItem()!=null){
                if(event.getButton().equals(MouseButton.PRIMARY)&&event.getClickCount()==2&&
                        tableView.getSelectionModel().getSelectedIndex()<tableView.getItems().size()){
                    showPassItem(tableView.getSelectionModel().getSelectedItem());
                    if(Boolean.valueOf(Cache.getOc().getAutoClearPanel())){
                           /* Runnable runnable = () -> {
                            showPassItem(null);
                            if(!service.isShutdown()){
                                service.shutdown();
                            }
                        };
                        long time=Long.valueOf(Cache.oc.getAutoClearPanelTime());

                        service.schedule(runnable, time, TimeUnit.SECONDS);*/
                    }

                }else if(event.getButton().equals(MouseButton.PRIMARY)&&event.getClickCount()==1&&
                        tableView.getSelectionModel().getSelectedIndex()<tableView.getItems().size()){
                    PasswordItem selectedItem = tableView.getSelectionModel().getSelectedItem();
                    showPassItem(null);
                    showBeizhu.setText(selectedItem.getRemarkStr());

                }else{
                    //防止误操作影响其他地方的复制信息
                    if(StringUtils.isNotBlank(showUsername.getText())){
                        Clipboard clipboard=Clipboard.getSystemClipboard();
                        ClipboardContent cc=new ClipboardContent();
                        cc.putString("");
                        clipboard.setContent(cc);
                        showPassItem(null);
                    }

                }
            }
        });
        //初始化列表右键菜单
        initPassItemRightContextMenu();
    }

    private void initPassItemRightContextMenu() {
        final ContextMenu contextMenu = new ContextMenu();
        MenuItem delete = new MenuItem("删除");
        delete.setOnAction((ActionEvent e) -> {

            PasswordItem selectedItem = tableView.getSelectionModel().getSelectedItem();
            if(selectedItem==null){
                CommonUtil.alert(Alert.AlertType.WARNING,"操作无效","请将鼠标放在要修改的密码项上再点击鼠标右键！","错误").show();
                return;
            }
            Alert alert=new Alert(Alert.AlertType.CONFIRMATION);
            alert.setHeaderText("确定要删除么？");
            alert.setContentText("密码条目删除后无法恢复！");
            Optional<ButtonType> showAndWait = alert.showAndWait();
            if(showAndWait.get().getButtonData()== ButtonBar.ButtonData.OK_DONE){
                try {
                    //执行删除逻辑
                    if(pd.deletePasswordItem(selectedItem)){
                        tableView.getItems().remove(selectedItem);
                    }
                } catch (SQLException ex) {
                    CommonUtil.alert(Alert.AlertType.ERROR,"删除密码条目失败","删除密码条目时发生系统错误！错误信息："+
                            ex.getMessage(),"错误").showAndWait();
                }catch(ClassNotFoundException ex){
                    CommonUtil.alert(Alert.AlertType.ERROR,"删除密码条目失败","找不到数据库驱动！错误信息："+
                            ex.getMessage(),"错误").showAndWait();
                }
            }

        });
        MenuItem edit = new MenuItem("修改");
        edit.setOnAction((ActionEvent e) -> {
            PasswordItem selectedItem = tableView.getSelectionModel().getSelectedItem();
            if(selectedItem==null){
                CommonUtil.alert(Alert.AlertType.WARNING,"操作无效","请将鼠标放在要修改的密码项上再点击鼠标右键！","错误").show();
                return;
            }
            try {
                updatePassItemBtnHandler(selectedItem);
            } catch (SQLException ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,"修改密码条目失败","修改密码条目时发生系统错误！错误信息："+
                        ex.getMessage(),"错误").showAndWait();
            }catch(ClassNotFoundException ex){
                CommonUtil.alert(Alert.AlertType.ERROR,"修改密码条目失败","找不到数据库驱动！错误信息："+
                        ex.getMessage(),"错误").showAndWait();
            }
        });

        MenuItem copyAccount = new MenuItem("复制账号");
        copyAccount.setOnAction((ActionEvent e) -> {
            PasswordItem selectedItem = tableView.getSelectionModel().getSelectedItem();
            if(selectedItem==null){
                CommonUtil.alert(Alert.AlertType.WARNING,"操作无效","请将鼠标放在要修改的密码项上再点击鼠标右键！","错误").show();
                return;
            }
            TextField textField = new TextField(selectedItem.getAccount());
            textField.selectAll();
            textField.copy();
        });

        MenuItem copyPass = new MenuItem("复制密码");
        copyPass.setOnAction((ActionEvent e) -> {
            PasswordItem selectedItem = tableView.getSelectionModel().getSelectedItem();
            if(selectedItem==null){
                CommonUtil.alert(Alert.AlertType.WARNING,"操作无效","请将鼠标放在要修改的密码项上再点击鼠标右键！","错误").show();
                return;
            }
            TextField textField = null;
            try {
                textField = new TextField(SecurityController.getSecurityInstence().AESdecrypt(selectedItem.getPasswordStr(), Cache.getKey()));
            } catch (Exception ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,"复制失败","复制密码时发生错误！错误信息："+ex.getMessage(),"错误").showAndWait();
                return;
            }
            textField.selectAll();
            textField.copy();
        });


        contextMenu.getItems().addAll(edit,copyAccount,copyPass,delete);
        tableView.setContextMenu(contextMenu);
    }

    private void updatePassItemBtnHandler(PasswordItem passwordItem) throws SQLException, ClassNotFoundException {
        PasswordItem pi=pd.getPasswordItemFromPassId(passwordItem.getPassId());
        String _itemDirTypeId=pi.getDirTypeId();
        Cache.setIndexLeftSelectedDirtype(classType.getSelectionModel().getSelectedItem());
        boolean okClicked = start.showPassEditDialog(pi);
        if(okClicked){
            PasswordItem selectedItem = tableView.getSelectionModel().getSelectedItem();
            if(!StringUtils.equals(_itemDirTypeId, pi.getDirTypeId())){
                tableView.getItems().remove(selectedItem);
                return;
            }
            String um = null;
            try {
                um = SecurityController.getSecurityInstence().AESdecrypt(pi.getAccount(), Cache.getKey());
            } catch (Exception ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,"更新失败","更新失败！错误信息："+ex.getMessage(),"错误").showAndWait();
                return;
            }
            pi.setAccount(um);
            tableView.getItems().remove(selectedItem);
            tableView.getItems().add(pi);
            //classType.setUserData(CommonUtil.ADD_PASS_ITEM_SELECT_DIRTYPE);
        }else{
            try {
                //修改失败需要还原账号
                pi.setAccount(SecurityController.getSecurityInstence().AESdecrypt(pi.getAccount(), Cache.getKey()));
            } catch (Exception ex) {
                CommonUtil.alert(Alert.AlertType.ERROR,"恢复错误","恢复密码项目出现错误！错误信息："+ex.getMessage(),"错误").showAndWait();
            }
        }
    }

    private void showPassItem(PasswordItem selectedItem) {
        if(selectedItem==null){
            showUsername.setText("");
            showPass.setText("");
            showBeizhu.setText("");
        }else{
            showUsername.setText(selectedItem.getAccount());
            showPass.setText("*********");
            showBeizhu.setText(selectedItem.getRemarkStr());
        }
    }

    public void startKongXianLock() {
        //如果开启了空闲锁定
        BackService.startClockService(lockBtn);
    }
}
